package com.mall.b2c.plugin.order;

import java.math.BigDecimal;

import com.mall.b2c.bean.PayInfo;
import com.mall.b2c.domain.member.MemberDomain;
import com.mall.b2c.domain.order.OrderDomain;

/**
 * 现金支付
 * @author fangchen
 *
 */
public class CashPayPlugin extends AbstractOrderPayPlugin implements IOrderPayEvent {

	@Override
	public BigDecimal beforePay(OrderDomain order, MemberDomain member, BigDecimal total, BigDecimal shipFee, PayInfo payInfo) {
		if(shipFee != null){
			total = total.add(shipFee);
		}
		BigDecimal totalCount = member.getDeposit();
		if(payInfo.getUseDeposit() != null
				&& payInfo.getUseDeposit()){
			if(total.compareTo(totalCount) > 0){
				total = total.subtract(totalCount);
				totalCount = BigDecimal.ZERO;
			}else{
				totalCount = totalCount.subtract(total);
				total = BigDecimal.ZERO;
			}
		}
		member.setDeposit(totalCount);
		payInfo.setCash(total);
		order.setCash(total);
		return total;
	}

	@Override
	public String afterPay(OrderDomain order, MemberDomain member) {
		BigDecimal count = order.getDeposit();
		if(count == null || count.signum() <= 0){
			count = BigDecimal.ZERO;
		}
		BigDecimal memberCount = member.getDeposit();
		if(count.signum() > 0
				&& (memberCount == null || count.compareTo(memberCount) > 0)){
			return "当前余额不足";
		}else if(count.signum() > 0
				&& memberCount != null
				&& count.compareTo(memberCount) <= 0){
			memberCount = memberCount.subtract(count);
		}
		count = order.getCash();
		if(count == null || count.signum() <= 0){
			count = BigDecimal.ZERO;
		}
		if(count.signum() > 0
				&& (memberCount == null || count.compareTo(memberCount) > 0)){
			return "当前余额不足";
		}else if(count.signum() > 0
				&& memberCount != null
				&& count.compareTo(memberCount) <= 0){
			memberCount = memberCount.subtract(count);
		}
		member.setDeposit(memberCount);
		return null;
	}
	
	@Override
	public String getPayError() {
		if(VALID_ERROR_NO_ENOUGH_COUNT.equals(type)){
			return "会员余额不足!";
		}else{
			return super.getPayError();
		}
	}
	
	@Override
	public String getType() {
		return "orderPay";
	}

	@Override
	public String getId() {
		return "cashPayPlugin";
	}

	@Override
	public String getName() {
		return "现金支付";
	}

	@Override
	public String getVersion() {
		return "1.0.0";
	}

	@Override
	public String getAuthor() {
		return "fangchen";
	}

	@Override
	public void perform(Object... params) {
		
	}

	@Override
	public void register() {
		
	}

}
